<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="文件路径" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="filePath">
              <a-upload
                :headers="tokenHeader"
                action="/jeecg-boot/dcloud-flink-stream-platform/api/uploadfile/v1/upload"
                :default-file-list="defaultFileList"
                :multiple="false"
                @change="uploadFile"
                :beforeUpload="beforeUpload"
              >
                <a-button> <a-icon type="upload" /> Upload </a-button>
              </a-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="类型（JOB/UDF）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="type">
              <a-select placeholder="请输入类型（JOB/UDF）:" v-model="model.type" >
                <a-select-option :value=1 >JOB</a-select-option>
                <a-select-option :value=2 >UDF</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import Vue from 'vue'
  import { ACCESS_TOKEN, TENANT_ID } from '@/store/mutation-types'

  export default {
    name: 'UploadFileForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model:{
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
           type: [
              { required: true, message: '请输入1:jar 2：udf!'},
           ],
           isDeleted: [
              { required: true, message: '请输入isDeleted!'},
           ],
        },
        url: {
          add: "/dcloud-flink-stream-platform/api/uploadfile/v1/add",
          edit: "/com.dcloud.streamweb/uploadFile/edit",
          queryById: "/com.dcloud.streamweb/uploadFile/queryById"
        },
        defaultFileList: []
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
      //token header
      tokenHeader(){
        let head = {'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)}
        let tenantid = Vue.ls.get(TENANT_ID)
        if(tenantid){
          head['tenant-id'] = tenantid
        }
        return head;
      }
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      uploadFile(info){
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          // 文件上传成功
          // 处理服务器返回的信息
          let res = info.file.response
          this.model.filePath =res.result
          this.model.fileName = info.file.name
        } else if (info.file.status === 'error') {
          // 文件上传失败
          console.error('文件上传失败', info.file.response);
        }

      },
      beforeUpload(file){

        let fileType = file.name.split('.').pop()
        const isJar = fileType === 'jar';
        if (!isJar) {
          this.$message.error('You can only upload JAR files!');
        }
        return isJar || Upload.abort;
      },
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.model = Object.assign({}, record);
        let param =
        {
          uid: '1',
          name: this.model.fileName,
          status: 'done',
          url: this.model.filePath,
        }
        this.defaultFileList.push(param)
        this.visible = true;
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
    }
  }
</script>